#!/bin/bash

# 获取脚本所在目录
# SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" && pwd )
SCRIPT_PATH=$(realpath "$0")
echo SCRIPT_PATH=$SCRIPT_PATH

# 获取脚本所在目录
SCRIPT_DIR=$( cd -- "$( dirname -- "${SCRIPT_PATH}" )" && pwd )
echo SCRIPT_DIR=$SCRIPT_DIR

# 获取上一级目录
PARENT_DIR=$(dirname "$SCRIPT_DIR")

LLVM_PROJECT=$1
BUILD_ROOT=$PARENT_DIR/build
INSTALL_ROOT=$PARENT_DIR/install


if [ -z "$LLVM_PROJECT" ]; then
    echo "需要传入LLVM工程目录"
fi

BUILD_TYPE=Debug

GEN_TARGET=Ninja

BUILD_DIR="$BUILD_ROOT/$GEN_TARGET/$BUILD_TYPE"
INSTALL_DIR="${INSTALL_ROOT}/$GEN_TARGET/${BUILD_TYPE}"

if [ ! -d "$BUILD_DIR" ]; then
    mkdir -p "$BUILD_DIR"
fi

if [ ! -d "$INSTALL_DIR" ]; then
    mkdir -p "$INSTALL_DIR"
fi

LLVM_ENABLE_PROJECTS="clang;lldb;lld"

# if [ "$os_name" = "Darwin" ]; then
#     CMAKE_BIN=/Users/aserlili-m1/Downloads/cmake-3.31.5-macos-universal/CMake.app/Contents/bin/cmake
# else
#     CMAKE_BIN=cmake
# fi

# LLDB_INCLUDE_TESTS设置为OFF意味着不需要测试套件
# 下面的 -DCLANG_BUILD_EXAMPLES=ON 和 -DCLANG_PLUGIN_SUPPORT=ON 是为了构建 clang/examples 里面的代码
$CMAKE_BIN -S $LLVM_PROJECT/llvm -B $BUILD_DIR \
    -G $GEN_TARGET \
    -DLLDB_INCLUDE_TESTS=OFF \
    -DLLDB_USE_SYSTEM_DEBUGSERVER=ON \
    -DCLANG_BUILD_EXAMPLES=ON \
    -DCLANG_PLUGIN_SUPPORT=ON \
    -DLLVM_ENABLE_PROJECTS=\'"${LLVM_ENABLE_PROJECTS}"\' \
    -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} \
    -DCMAKE_BUILD_TYPE=$BUILD_TYPE \
    -DCMAKE_C_COMPILER=$(which clang) \
    -DCMAKE_CXX_COMPILER=$(which clang++) \
